/******************************
  this is a app to show a muti thread tcp server
  ****************************/

#include"TCPServer.h"
#include <string.h>
#include <pthread.h>
const int TCPBUFFER=1024;
const int SOCKETTIMEOUT=1200; //ms

static void *threadRun(void *arg) //handle in the thread
{ 
	pthread_detach(pthread_self()); 
	TCPServer *thdSocket=(TCPServer *)arg;
	thdSocket->initm_bConnect(true);
	printf("new client addr: %s port:%d \n",thdSocket->socketIP(),thdSocket->socketPort());

	char bufRev[TCPBUFFER+1]={0};
	char bufSend[TCPBUFFER+1]={0};
	memset(bufRev,0,sizeof(bufRev));
	memset(bufSend,0,sizeof(bufSend));
	while(1)
	{
		if(thdSocket->receiveAllData(bufRev,SOCKETTIMEOUT)>0) //recv
		{
			printf("get:%s\n",bufRev);
			memset(bufSend,0,sizeof(bufSend));
			memcpy(bufSend,bufRev,sizeof(bufSend));
			memset(bufRev,0,sizeof(bufSend));
			int sendNum=thdSocket->sendData(bufSend,strlen(bufSend),SOCKETTIMEOUT);
			printf("send bytes: %d!\n",sendNum);
			break;
		}
	}
	thdSocket->closeTcpSocket();
	delete thdSocket;
	pthread_exit(0);
} 

int main()
{
	TCPServer server;
	struct sockaddr_in clientAddr;
	pthread_t tid;
	if(server.setListenPort(12345))
	{
		while(1)
		{
			TCPServer *tempSocket=new TCPServer;
			if(server.setAccept(tempSocket,(struct sockaddr*)&clientAddr,SOCKETTIMEOUT)>0)//new connection
			{
				tempSocket->setIpAdd(inet_ntoa(clientAddr.sin_addr));//set client ip
				tempSocket->setPort(clientAddr.sin_port);//set client port
				pthread_create(&tid,NULL,threadRun,(void*)tempSocket); //create thread to handle new connection
			}
			else
			{
				delete tempSocket;
			}
		}
	}
	server.closeTcpSocket();
	return 0;
}
